package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"zhihu/models/cache"
	"zhihu/models/mysql"

	"zhihu/zhihuRpc/internal/svc"
	"zhihu/zhihuRpc/zhihuRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type QuestionHotListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQuestionHotListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionHotListLogic {
	return &QuestionHotListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QuestionHotListLogic) QuestionHotList(in *zhihuRpc.QuestionHotListRequest) (*zhihuRpc.QuestionHotListResponse, error) {
	// todo: add your logic here and delete this line

	var questions []mysql.Question
	key := fmt.Sprintf("questionHotList")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		mysql.DB.Debug().Limit(10).Order("hot desc").Find(&questions)
		marshal, _ := json.Marshal(questions)

		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &questions)
	}

	var questionList []*zhihuRpc.QuestionHotList

	for _, question := range questions {
		list := zhihuRpc.QuestionHotList{
			Id:      int64(question.ID),
			Content: question.Content,
			UserId:  question.UserId,
			Hot:     question.Hot,
		}

		questionList = append(questionList, &list)
	}

	return &zhihuRpc.QuestionHotListResponse{
		List: questionList,
	}, nil
}
